package com.ea.modular.utils.sys;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ea.common.utils.FileUtil;
import com.ea.common.utils.StrKit;
import com.ea.modular.model.sys.GenerateInput;





public class TemplateUtil {

	private static final Logger log = LoggerFactory.getLogger("adminLogger");

	public static String getTemplete(String fileName) {
		return FileUtil.getText(TemplateUtil.class.getClassLoader().getResourceAsStream("generate/" + fileName));
	}

	public static void saveJava(GenerateInput input) {
		String path = input.getPath();
		String beanPackageName = input.getBeanPackageName();
		String beanName = input.getBeanName();
		List<String> beanFieldName = input.getBeanFieldName();
		List<String> beanFieldType = input.getBeanFieldType();
		List<String> beanFieldValue = input.getBeanFieldValue();

		String text = getTemplete("java.txt");
		text = text.replace("{beanPackageName}", beanPackageName).replace("{beanName}", beanName);

		String imports = "";
		if (beanFieldType.contains(BigDecimal.class.getSimpleName())) {
			imports += "import " + BigDecimal.class.getName() + ";\n";
		}
		if (beanFieldType.contains(Date.class.getSimpleName())) {
			imports += "import " + Date.class.getName() + ";";
		}

		text = text.replace("{import}", imports);
		String filelds = getFields(beanFieldName, beanFieldType, beanFieldValue);
		text = text.replace("{filelds}", filelds);
		text = text.replace("{getset}", getset(beanFieldName, beanFieldType));

		FileUtil.saveTextFile(text, path + File.separator + getPackagePath(beanPackageName) + beanName + ".java");
		log.debug("生成java model：{}模板", beanName);
	}

	private static String getFields(List<String> beanFieldName, List<String> beanFieldType,
			List<String> beanFieldValue) {
		StringBuffer buffer = new StringBuffer();
		int size = beanFieldName.size();
		for (int i = 0; i < size; i++) {
			String name = beanFieldName.get(i);
			if ("id".equals(name) || "createBy".equals(name) || "createDate".equals(name)|| "updateDate".equals(name)|| "updateBy".equals(name)|| "remarks".equals(name)|| "delFlag".equals(name)) {
				continue;
			}
			String type = beanFieldType.get(i);
			buffer.append("\tprivate ").append(type).append(" ").append(name);
			
			buffer.append(";\n");
		}

		return buffer.toString();
	}

	private static String getset(List<String> beanFieldName, List<String> beanFieldType) {
		StringBuffer buffer = new StringBuffer();
		int size = beanFieldName.size();
		for (int i = 0; i < size; i++) {
			String name = beanFieldName.get(i);
			if ("id".equals(name) || "createBy".equals(name) || "createDate".equals(name)|| "updateDate".equals(name)|| "updateBy".equals(name)|| "remarks".equals(name)|| "delFlag".equals(name)) {
				continue;
			}

			String type = beanFieldType.get(i);
			buffer.append("\tpublic ").append(type).append(" get")
					.append(StringUtils.substring(name, 0, 1).toUpperCase() + name.substring(1, name.length()))
					.append("() {\n");
			buffer.append("\t\treturn ").append(name).append(";\n");
			buffer.append("\t}\n");
			buffer.append("\tpublic ").append("void").append(" set")
					.append(StringUtils.substring(name, 0, 1).toUpperCase() + name.substring(1, name.length()))
					.append("("+ type +" "+lowerFirstChar(name)+") {\n");
			buffer.append("\t\t this."+lowerFirstChar(name)+"=").append(lowerFirstChar(name)).append(";\n");
			buffer.append("\t}\n");
		}

		return buffer.toString();
	}

	public static void saveJavaDao(GenerateInput input) {
		String path = input.getPath();
		String tableName = input.getTableName();
		String beanPackageName = input.getBeanPackageName();
		String beanName = input.getBeanName();
		String daoPackageName = input.getDaoPackageName();
		String daoName = input.getDaoName();

		String text = getTemplete("dao.txt");
		text = text.replace("{daoPackageName}", daoPackageName);
		text = text.replace("{beanPackageName}", beanPackageName);
		text = text.replace("{daoName}", daoName);
		text = text.replace("{table_name}", tableName);
		text = text.replace("{beanName}", beanName);
		text = text.replace("{beanParamName}", lowerFirstChar(beanName));

		
		FileUtil.saveTextFile(text, path + File.separator + getPackagePath(daoPackageName) + daoName + ".java");
		log.debug("生成java dao：{}模板", beanName);

		text = getTemplete("mapper.xml");
		text = text.replace("{daoPackageName}", daoPackageName);
		text = text.replace("{daoName}", daoName);
		text = text.replace("{table_name}", tableName);
		text = text.replace("{beanName}", beanName);
		text = text.replace("{beans}", getBeans(input.getColumnNames()));
		String sets = getUpdateSets(input.getColumnNames(), input.getBeanFieldName());
		text = text.replace("{update_sets}", sets);
		String where = getWhere(input.getColumnNames(), input.getBeanFieldName());
		text = text.replace("{where}", where);
		String insertColumns = getInsertColumns(input.getColumnNames());
		text = text.replace("{insert_columns}", insertColumns);
		String insertValues = getInsertValues(input.getColumnNames(), input.getBeanFieldName());
		text = text.replace("{insert_values}", insertValues);
		FileUtil.saveTextFile(text, path + File.separator + beanName + "Mapper.xml");
	}
	
	public static void saveJavaService(GenerateInput input) {
		String path = input.getPath();
		String beanPackageName = input.getBeanPackageName();
		String beanName = input.getBeanName();
		String daoPackageName = input.getDaoPackageName();
		String daoName = input.getDaoName();
		String servicePackageName=input.getServicePkgName();
		String serviceName=input.getServiceName();

		String text = getTemplete("service.txt");
		text = text.replace("{daoPackageName}", daoPackageName);
		text = text.replace("{beanPackageName}", beanPackageName);
		text = text.replace("{daoName}", daoName);
		text = text.replace("{beanName}", beanName);
		text = text.replace("{servicePkgName}", servicePackageName);
		text = text.replace("{serviceName}", serviceName);
		
	
	
		FileUtil.saveTextFile(text, path + File.separator + getPackagePath(servicePackageName) + serviceName + ".java");
		log.debug("生成java service：{}模板", beanName);

		
	}
	
	

	private static String getInsertValues(List<String> columnNames, List<String> beanFieldName) {
		StringBuffer buffer = new StringBuffer();
		int size = columnNames.size();
		for (int i = 0; i < size; i++) {
			
		        if(beanFieldName.get(i).equals("createBy")||beanFieldName.get(i).equals("updateBy")) {
		        	buffer.append("#{").append(beanFieldName.get(i)).append(".id}, ");
		        }else {
		        	buffer.append("#{").append(beanFieldName.get(i)).append("}, ");
		        }
				
			
		}

		String sets = StringUtils.substringBeforeLast(buffer.toString(), ",");
		return sets;
	}

	private static String getInsertColumns(List<String> columnNames) {
		StringBuffer buffer = new StringBuffer();
		int size = columnNames.size();
		for (int i = 0; i < size; i++) {
			String column = columnNames.get(i);
			
				buffer.append(column).append(", ");
			
		}

		String insertColumns = StringUtils.substringBeforeLast(buffer.toString(), ",");
		return insertColumns;
	}

	private static String getUpdateSets(List<String> columnNames, List<String> beanFieldName) {
		StringBuffer buffer = new StringBuffer();
		int size = columnNames.size();
		for (int i = 0; i < size; i++) {
			String column = columnNames.get(i);
			if (!"id".equals(column)&&!"create_by".equals(column)&&!"create_date".equals(column)) {
				if("update_by".equals(column)||"update_date".equals(column)) {
					buffer.append("\t\t\t<if test=\"" + beanFieldName.get(i) + " != null\">\n");
				}else {
					buffer.append("\t\t\t<if test=\"" + column + " != null\">\n");
				}
				
				if(i==size-1) {
					if("update_by".equals(column)) {
						buffer.append("\t\t\t\t" + column).append(" = ").append("#{").append(beanFieldName.get(i))
						.append(".id} \n");
					}else {
						buffer.append("\t\t\t\t" + column).append(" = ").append("#{").append(beanFieldName.get(i))
						.append("} \n");
					}
				
				}else {
					if("update_by".equals(column)) {
						buffer.append("\t\t\t\t" + column).append(" = ").append("#{").append(beanFieldName.get(i))
						.append(".id}, \n");
					}else {
						buffer.append("\t\t\t\t" + column).append(" = ").append("#{").append(beanFieldName.get(i))
						.append("}, \n");
					}
					
				}
			
				buffer.append("\t\t\t</if>\n");
			}
		}

		return buffer.toString();
	}

	private static String getWhere(List<String> columnNames, List<String> beanFieldName) {
		StringBuffer buffer = new StringBuffer();
		int size = columnNames.size();
		for (int i = 0; i < size; i++) {
			String column = columnNames.get(i);
			if (!"remarks".equals(column)&&!"update_date".equals(column)&&!"update_by".equals(column)&&!"create_by".equals(column)&&!"create_date".equals(column)) {
				buffer.append("\t\t\t<if test=\"" + column + " != null and " + column + " != ''\">\n");
				buffer.append("\t\t\t\tand " + column).append(" = ").append("#{").append(beanFieldName.get(i))
						.append("} \n");
				buffer.append("\t\t\t</if>\n");
			}
			
		}

		return buffer.toString();
	}

	private static String getBeans(List<String> columnNames) {
		StringBuffer buffer = new StringBuffer();
		int size = columnNames.size();
		for (int i = 0; i < size; i++) {
			String column = columnNames.get(i);
            if(i==size-1) {
            	buffer.append("\t\t\t\t" + column+ "\n");
            }else {
            	buffer.append("\t\t\t\t" + column+ ",\n");
            }
			
		}

		return buffer.toString();
	}
	
	/**
	 * 变量名
	 * 
	 * @param beanName
	 * @return
	 */
	public static String lowerFirstChar(String beanName) {
		String name = StrKit.str2hump(beanName);
		String firstChar = name.substring(0, 1);
		name = name.replaceFirst(firstChar, firstChar.toLowerCase());

		return name;
	}

	private static String getPackagePath(String packageName) {
		String packagePath = packageName.replace(".", "/");
		if (!packagePath.endsWith("/")) {
			packagePath = packagePath + "/";
		}

		return packagePath;
	}

	public static void saveController(GenerateInput input) {
		String path = input.getPath();
		String beanPackageName = input.getBeanPackageName();
		String beanName = input.getBeanName();
		String servicePackageName = input.getServicePkgName();
		String serviceName = input.getServiceName();
        String pageName = input.getPagename();
        String pagepath=input.getPagepath();
		
		
		
		String text = getTemplete("controller.txt");
		text = text.replace("{servicePkgName}", servicePackageName);
		text = text.replace("{beanPackageName}", beanPackageName);
		text = text.replace("{serviceName}", serviceName);
		text = text.replace("{serviceParamName}", lowerFirstChar(serviceName));
		text = text.replace("{beanName}", beanName);
		text = text.replace("{beanParamName}", lowerFirstChar(beanName));
		text = text.replace("{controllerPkgName}", input.getControllerPkgName());
		text = text.replace("{controllerName}", input.getControllerName());
		text = text.replace("{pageName}", pageName);
		text = text.replace("{pagepath}", pagepath);
		FileUtil.saveTextFile(text, path + File.separator + getPackagePath(input.getControllerPkgName())
				+ input.getControllerName() + ".java");
		log.debug("生成controller：{}模板", beanName);
	}

	public static void saveHtmlList(GenerateInput input) {
		String path = input.getPath();
		
		String beanName = input.getBeanName();
		String beanParamName = lowerFirstChar(beanName);
        String pageName=input.getPagename();
        String jsPath=input.getJspath();
    	List<String> beanFieldNames = input.getBeanFieldName();

		String text = getTemplete("page.txt");
		text = text.replace("{beanName}", beanParamName);
		text = text.replace("{pageName}", pageName);
		text = text.replace("{jsPath}", jsPath);
	

		FileUtil.saveTextFile(text, path + File.separator + pageName + ".html");
		log.debug("生成查询页面：{}模板", pageName);

		text = getTemplete("page_add.txt");
		text = text.replace("{columnsDatas}", getHtmlColumnsDatas(beanFieldNames));
		text = text.replace("{beanName}", beanParamName);
		text = text.replace("{pageName}", pageName);
		text = text.replace("{jsPath}", jsPath);
		FileUtil.saveTextFile(text, path + File.separator + beanName + "_add .html");
		log.debug("生成添加页面：{}模板", beanName);

		text = getTemplete("page_edit.html.txt");
		text = text.replace("{columnsDatas}", getHtmlEditColumnsDatas(beanFieldNames));
		text = text.replace("{beanName}", beanParamName);
		text = text.replace("{pageName}", pageName);
		text = text.replace("{jsPath}", jsPath);
		FileUtil.saveTextFile(text, path + File.separator + beanName + "_update.html");
		log.debug("生成修改页面：{}模板", beanName);
	}

	
	public static void saveJavaScript(GenerateInput input){
		
        String path = input.getPath();
        String beanName = input.getBeanName();
        String pageName=input.getPagename();
		String beanParamName = lowerFirstChar(beanName);


    	List<String> beanFieldNames = input.getBeanFieldName();

		String text = getTemplete("page.js.txt");
		text = text.replace("{beanName}", beanParamName);
		text = text.replace("{pageColumns}", getJSColumnsDatas(beanFieldNames));
	

		FileUtil.saveTextFile(text, path + File.separator + pageName + ".js");
		log.debug("生成js页面：{}模板", beanName);
		
		
		
		
	    text = getTemplete("page_info.js.txt");
		text = text.replace("{beanName}", beanParamName);
		text = text.replace("{setDatas}", getJSDatas(beanFieldNames));
	

		FileUtil.saveTextFile(text, path + File.separator + pageName + "_info.js");
		log.debug("生成js页面：{}模板", beanName);
		
	}


	private static String getHtmlColumnsDatas(List<String> beanFieldNames) {
		StringBuilder builder = new StringBuilder();
		beanFieldNames.forEach(b -> {
			builder.append("\t\t\t\t<#input id='"+b+"' name='"+b+"' underline='true'  />\n");		
		});

		builder.append("");
		return builder.toString();
	}
	
	
	private static String getHtmlEditColumnsDatas(List<String> beanFieldNames) {
		StringBuilder builder = new StringBuilder();
		beanFieldNames.forEach(b -> {
			builder.append("\t\t\t\t<#input id='"+b+"' name='"+b+"' underline='true' value='${{beanName}."+b+"}'  />\n");		
		});

		builder.append("");
		return builder.toString();
	}
	
	private static String getJSColumnsDatas(List<String> beanFieldNames) {
		StringBuilder builder = new StringBuilder();
	

		int size = beanFieldNames.size();
		for (int i = 0; i < size; i++) {
			String column = beanFieldNames.get(i);
			if(!"id".equals(column)){
				if(i==size-1) {
	            	builder.append("\t\t\t\t {title: '"+column+"', field: '"+column+"', align: 'center', valign: 'middle', sortable: true}\n");
	            }else {
	            	builder.append("\t\t\t\t {title: '"+column+"', field: '"+column+"', align: 'center', valign: 'middle', sortable: true},\n");
	            }
			}
            
			
		}
		return builder.toString();
	}
	
	private static String getJSDatas(List<String> beanFieldNames) {
		StringBuilder builder = new StringBuilder();
	

		beanFieldNames.forEach(b -> {
			builder.append("\t\t\t\t.set('"+b+"')");		
		});

		builder.append("");
		return builder.toString();
	}

}
